zz_

gcd.js

thoward37@gmail.com/shirt[create-new-file-named-gcd-js-appropriate] / gcd.js @ 9a3429bb Download
Ladder Summary
  • file Add Euclidean GCD implementation with comprehensive tests
/**
 * Computes the greatest common divisor (GCD) of two integers using Euclid's algorithm.
 * Handles negative numbers and zero correctly.
 *
 * @param {number} a - First integer.
 * @param {number} b - Second integer.
 * @returns {number} The GCD of a and b. Returns 0 if both a and b are 0.
 */
export function gcd(a, b) {
    // Convert to absolute values to handle negatives
    a = Math.abs(a);
    b = Math.abs(b);

    // Euclidean algorithm
    while (b !== 0) {
        const temp = b;
        b = a % b;
        a = temp;
    }

    return a;
}